package com.thinkgem.jeesite.modules.lottery.mobile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.thinkgem.jeesite.common.utils.HMZUploadUtil;
import com.thinkgem.jeesite.common.utils.Result;
import com.thinkgem.jeesite.modules.lottery.entity.Material;
import com.thinkgem.jeesite.modules.lottery.service.MaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@Controller
@RequestMapping("/lottery/material")
public class MaterialMobileController {

    @Autowired
    private MaterialService materialService;

    @Value("${filepath}")
    private String filepath;
    @Value("${fileAccessPath}")
    private String fileAccessPath;
    @Value("${serverPath}")
    private String serverPath;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public Result upload(@RequestParam(value = "file", required = true) MultipartFile file, String openid) {
        if (file.isEmpty()) {
            return Result.error("文件上传失败（文件是空文件）");
        }
        try {
            String filename = HMZUploadUtil.upload(filepath, file, openid);
            ObjectMapper mapper = new ObjectMapper();
            Material material = new Material();
            material.setOpenid(openid);
            material.setImage(serverPath+filepath + filename);
            materialService.save(material);
            Result result = Result.ok("文件上传成功");
            result.put("image", serverPath+filepath + filename);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("文件上传失败");
        }
    }
}
